﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

namespace JsParser.Cmd.Code
{
    class FilePathsGenerator
    {
        public IEnumerable<string> GetFiles(Settings settings)
        {
            var includes = GetParts(settings.Include);
            var excludes = GetParts(settings.Exclude);
            return Directory.EnumerateFiles(settings.WorkingDirectory, "*.*", SearchOption.AllDirectories)
                .Where(x => includes.Any(a => a.IsMatch(x)))
                .Where(x => excludes.All(a => !a.IsMatch(x)));
        }

        private static IEnumerable<Regex> GetParts(string line)
        {
            return (line ?? string.Empty)
                .Split(new[] {";"}, StringSplitOptions.RemoveEmptyEntries)
                .Select(x => new Regex( BuildPattern(x), RegexOptions.Compiled|RegexOptions.IgnoreCase))
                .ToArray();
        }

        private static string BuildPattern(string x)
        {
            return x
                .Replace(".", "[.]")
                .Replace("*", ".*")
                .Replace("?", ".")
                .Replace("\\", "\\\\")
                   + "$";
        }
    }
}
